
 // 向医生提问

$(function() {

    //1.初始化
	$(window).on("load", initForm);
	
	//2.跳转咨询人列表页面
	$('#userId').on("click", toArchivesPage);
	
	//3.提交订单
	$("#submitQuestionBtn").on("click", submitConsultOrder);
	
	// 咨询订单对象
	function ConsultOrder() {
		var consultOrder;
		consultOrder = utilModule.dealFormFilter("askForm");
		console.log(consultOrder);
		return consultOrder;
	}

	//初始化form，订单基本信息：医生信息doctorid、  订单金额、 订单类型、
	
	/**
	 * 初始化该页面时，需要做相关的逻辑处理；
	 * 1.如果直接问医生，那么订单类型orderType则为1,同时医生详情接口需要获取医生的基本信息。存储订单信息【订单类型、医生id、订单金额、】
	 * 
	 * 2.如果从医生首页进入，则直接存对应的订单类型，医生基本信息即可，图文咨询orderType为1 如果是电话咨询orderType则为2，则需要获取最后一次接收的电话号码；存储订单信息【订单类型、医生id、订单金额、】
	 * 3.如果跳转到档案页面，则需要先存储订单基本信息【订单类型、医生id、订单金额、】，回调的时候再从session中获取
	 * 
	 */
	
	function initForm() {
		//初始化订单基本信息
		var doctor_info  = JSON.parse(sessionStorage.getItem("doctor_index"));
		console.log(doctor_info);
		$("#payAmount").val(doctor_info.payAmount);
		$("#doctorid").val(doctor_info.doctorid);
		$("#orderDetail").val(doctor_info.orderDetail);
		var orderType = doctor_info.orderType;
		$("#orderType").val(orderType);
		if(orderType == 1) {
			getUserarchives(2);
			$(".phoneService").show(); 
			$(".phoneService .none").hide();
			$(".phone-consult").hide();
			$("#textDiv").text("图文咨询")
			$("#showPrice").text("￥" + doctor_info.payAmount);
		} else if(orderType == 2) {
			//getLastOrderInfo();
			$(".graphic-consult").hide();
			$(".phoneService").show();
			getUserarchives(2);
			$("#textDiv").text("电话咨询");
			$("#showPrice").text("￥" + doctor_info.payAmount);
			var datetime = doctor_info.serviceTime;
			var date =datetime.substring(11,22);
			var dates=date.split("-");
			//console.log(dates[0]);
			$("#startTime").text(dates[0]);
			$("#endTime").text(dates[1]);
			$("#serviceTime").text(doctor_info.serviceTime);
			$("input[name='serviceTime']").val(doctor_info.serviceTime);
		} 
		function advocateInfor () {
			mui.alert("请先选择咨询人", "提示","好的");
			return false;
		}
		var Aname = $("#advocateName").text();
		if(utilModule.checkUndefined(Aname)==""){ 
			$(".textarea textarea").on("tap",function(event){
				event.preventDefault();
				advocateInfor();
				event.preventDefault();
			});
			$(".camera-area .thumb .addFile .add input").on("tap",function(event){
				event.preventDefault();
				advocateInfor();
				event.preventDefault();
			});		
		}
	}
	 //初始化 档案
	function getInitadvocate() {
		var initadvocateInfo = sessionStorage.getItem("archives_info_key");
		if(initadvocateInfo != null) {
			initadvocateInfo = JSON.parse(initadvocateInfo);
			$("#advocateName").text(initadvocateInfo.name);
			$(".advocateAge").html(initadvocateInfo.age + "岁");
			$(".advocateSex").text(initadvocateInfo.sex);
			$("#answerPhone").text(initadvocateInfo.phone);
			$("#archivesId").val(initadvocateInfo.archivesId);
		}
		return  initadvocateInfo==null?false:true;
	}
	
	//获取档案
	function getUserarchives(){
		var results = getInitadvocate();
		if(results==false){
			var params={userid:USERID,type:2};
			orderPayModule.queryLastArchivesidByUserid(params, function(callBack) {
				console.log(callBack)
				var data = callBack;
				if(utilModule.checkUndefined(data.age) != "") {
					$("#archivesId").val(data.archivesid);
					$("#advocateName").text(data.name);
					if(data.sex==1){
						$(".advocateSex").text("男");
					}else{
						$(".advocateSex").text("女");
					}
					$(".advocateAge").text(data.age+"岁");
					$("#answerPhone").text(data.phoneNumber);
				}
			});
		}
	
	}
	//获取最后一次电话咨询订单信息
//	function getLastOrderInfo() {
//		var params = {
//			id: USERID,
//		};
//		doctorModule.getLastOrderByUserid(params, function(callBack) {
//			var data = callBack;
//			console.log(data);
//			if(data != null) {
//				$("#answerPhone").text(data.answerPhone);
//			} else {
//				$(".question-time .number").find("font").text("输入号码");
//			}
//		});
//	}
	//跳转档案列表
	function toArchivesPage(){
		sessionStorage.setItem("skipType","2");
		location.href="../service/user-archives-list.html";   
	}
	
	//提交问题
	function submitConsultOrder() {
		var Aname = $("#advocateName").text();
	  	if(Aname.trim()==""){
			mui.alert("请选择咨询人","提示");
			return false;
		}
		//提问
		var questionBody = $("#questionbody").val().replace(/\s+/g,"");
		var answerPhone = $("#answerPhone").text();
		var orderType = $("#orderType").val();
		
		var reg = /^1[34578]\d{9}$/;
		if(orderType== 2 && answerPhone == "") {
			mui.alert("预约电话不能为空!", "提示");
			return false;
		} else if(orderType == 2 && !(reg.test(answerPhone))) {
			mui.alert("手机号码格式有误，请重填", "提示");
			return false;
		}
		if(questionBody == null || questionBody == "") {
			mui.alert("问题不能为空", "提示");
			return false;
		} else if(utilModule.countStringLength(questionBody) > 200) {
			mui.alert("问题字数不能超过200个字符", "提示");
			return false;
		}

		//获取附件
		var questionfilesObject = $("input[name='questionFiles']").length;
		var questionfiles = "";
		$("input[name='questionFiles']").each(function() {
			questionfiles += $(this).val() + ",";
		});
		var consultOrder = ConsultOrder();
		consultOrder.userid = USERID;
		consultOrder.openid = OPENID;
		consultOrder.questionfiles = questionfiles;
		consultOrder.answerPhone = answerPhone;
		console.log(consultOrder);
		var doctor_info  = JSON.parse(sessionStorage.getItem("doctor_index"));
		var consultOrde = $.extend(true, doctor_info,consultOrder);
		if(consultOrde.orderType == 1) {
			submitTextOrder(consultOrde);
		}
		if(consultOrde.orderType == 2){
		    submitPhoneOrder(consultOrde);
		}
			
	}
	//提交图文咨询订单
	function submitTextOrder(orderParam) {
		askDoctorModule.submitOrder(orderParam, function(callBack) {
			var data = callBack;
			console.log(data);
			if(data != null) {
				//如果免费咨询，则直接跳转聊天界面
				var payAmount = orderParam.payAmount;
				if(payAmount == 0.00 || payAmount == 0) {
					invokeIm(data, orderParam.doctorid);
				} else {
					mui.toast("下单成功!");
					location.replace("../order/order-pay.html?orderType=1&orderid=" + data)
				}
			}
		});
	}
	//图文咨询聊天
	function invokeIm($orderid, $doctorid) {
		var orderid = $orderid;
		var params = {
			"doctorId": $doctorid
		};
		var doctorIm = "";
		var payStatus = 2; //免費咨詢	
		/**查询订单明细 **/
		var orderInfo = queryTextOrderDetail($orderid);
		doctorModule.queryDetail(params, function(callBack) {
			var result = callBack;
			if(result != null) {
				var doctorInfo = result.doctor;
				//doctor_user_20
				var doctorObject = {};
				doctorObject.doctorid = doctorInfo.id;
				var usernameIM =DOCTOR_IM_PREFFIX+ doctorInfo.id;
				doctorObject.usernameIM = usernameIM;
				doctorObject.avatar = doctorInfo.avatar;
				doctorObject.realname = doctorInfo.realname;
				doctorObject.deptName = doctorInfo.deptName;
				utilModule.setStorage(usernameIM, JSON.stringify(doctorObject));
				//清空与该医生之前的聊天记录
				var chatList = utilModule.getStorage("chat_list");
				if(chatList != null) {
					var chatObject = JSON.parse(chatList);
					var rd_key = DOCTOR_IM_PREFFIX + doctorInfo.id;
					delete chatObject[rd_key];
					var $chatObject = JSON.stringify(chatObject);
					utilModule.setStorage("chat_list", $chatObject);

				}
				//获取提问的内容信息
				//支付成功跳转im聊天界面 payStatus: 2:图文订单
				var questionbody = orderInfo.questionbody;
				var ext = orderInfo.membersex + ":" + orderInfo.memberbirthday;

				var toImUrl = "../inquiry/inquiry-service.html?usernameIM=" + usernameIM + "&orderid=" + orderid + "&payStatus=" + payStatus+"&doctorid="+doctorInfo.id;
				toImUrl += "&msg=" + encodeURIComponent(questionbody) + "&ext=" + ext;

				mui.toast("正在跳转咨询界面....");
				console.log("医生信息:" + utilModule.getStorage(usernameIM));
				//支付成功跳转im聊天界面 payStatus: 2 图文咨询

				location.replace(toImUrl);
			}
		});
	}
	//图文咨询订单详情
	function queryTextOrderDetail(params) {
		var params = {
			id: params
		};
		var result = null;
		orderPayModule.queryOrderDetail(params,
			function(callBack) {
				var orderInfo = callBack;
				if(orderInfo != null) {
					result = orderInfo;
				}
			});
		return result;
	}
	 
	//提交电话咨询订单
	function submitPhoneOrder(orderParam) {
		orderParam.price = orderParam.payAmount;
		console.log(orderParam);
		askDoctorModule.submitPhoneOrder(orderParam, function(callBack) {
			var data = callBack;
			console.log(data);
			if(data != null) {
				mui.toast("预约成功!");
				location.replace("../order/order-pay.html?orderType=2&orderid=" + data)
			}
		});
	}

});